import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import subprocess
import schedule
import time
import threading
import os

class GitAutoUpdater:
    def __init__(self, root):
        self.root = root
        self.root.title("Git自动更新工具")
        self.root.geometry("500x320")
        self.root.resizable(False, False)
        
        # 设置中文字体
        self.font = ('SimHei', 10)
        
        # 获取脚本所在目录（默认作为仓库路径）
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        
        # 变量初始化
        self.repo_path = tk.StringVar(value=self.script_dir)
        self.interval = tk.StringVar(value="5")  # 默认5分钟
        self.is_running = False
        self.schedule_thread = None
        
        self.create_widgets()
    
    def create_widgets(self):
        # 仓库路径选择
        path_frame = ttk.Frame(self.root)
        path_frame.pack(pady=10, fill=tk.X, padx=20)
        
        ttk.Label(path_frame, text="仓库路径:", font=self.font).pack(side=tk.LEFT, padx=5)
        
        path_entry = ttk.Entry(path_frame, textvariable=self.repo_path, width=30, font=self.font)
        path_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        browse_btn = ttk.Button(path_frame, text="浏览", command=self.browse_repo)
        browse_btn.pack(side=tk.LEFT, padx=5)
        
        # 路径类型提示
        hint_frame = ttk.Frame(self.root)
        hint_frame.pack(pady=5, fill=tk.X, padx=20)
        
        ttk.Label(
            hint_frame, 
            text=f"当前使用: {'相对路径（脚本所在目录）' if self.is_repo_in_script_dir() else '绝对路径'}", 
            font=('SimHei', 9),
            foreground="#666666"
        ).pack(anchor=tk.W)
        
        # 时间间隔设置
        interval_frame = ttk.Frame(self.root)
        interval_frame.pack(pady=10, fill=tk.X, padx=20)
        
        ttk.Label(interval_frame, text="更新间隔(分钟):", font=self.font).pack(side=tk.LEFT, padx=5)
        
        interval_entry = ttk.Entry(interval_frame, textvariable=self.interval, width=10, font=self.font)
        interval_entry.pack(side=tk.LEFT, padx=5)
        
        # 日志区域
        log_frame = ttk.Frame(self.root)
        log_frame.pack(pady=10, fill=tk.BOTH, expand=True, padx=20)
        
        ttk.Label(log_frame, text="操作日志:", font=self.font).pack(anchor=tk.W)
        
        self.log_text = tk.Text(log_frame, height=8, width=50, state=tk.DISABLED, font=self.font)
        self.log_text.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(self.log_text, command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)
        
        # 控制按钮
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=10)
        
        self.start_btn = ttk.Button(btn_frame, text="开始", command=self.start_updating)
        self.start_btn.pack(side=tk.LEFT, padx=10)
        
        self.stop_btn = ttk.Button(btn_frame, text="停止", command=self.stop_updating, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=10)
        
        self.run_once_btn = ttk.Button(btn_frame, text="立即执行", command=self.run_once)
        self.run_once_btn.pack(side=tk.LEFT, padx=10)
        
        # 初始化检查
        self.check_repo_status()
    
    def is_repo_in_script_dir(self):
        """检查当前仓库路径是否是脚本所在目录"""
        return os.path.abspath(self.repo_path.get()) == self.script_dir
    
    def check_repo_status(self):
        """检查当前路径是否是Git仓库并记录日志"""
        if os.path.isdir(os.path.join(self.repo_path.get(), ".git")):
            self.log(f"已自动检测到仓库路径: {self.repo_path.get()}")
        else:
            self.log("提示: 当前路径不是Git仓库，请选择正确的仓库目录")
    
    def browse_repo(self):
        """浏览选择仓库路径"""
        path = filedialog.askdirectory(title="选择Git仓库目录", initialdir=self.script_dir)
        if path:
            self.repo_path.set(path)
            # 更新路径类型提示
            for widget in self.root.winfo_children():
                if isinstance(widget, ttk.Frame) and len(widget.winfo_children()) == 1:
                    child = widget.winfo_children()[0]
                    if isinstance(child, ttk.Label) and "当前使用:" in child["text"]:
                        child["text"] = f"当前使用: {'相对路径（脚本所在目录）' if self.is_repo_in_script_dir() else '绝对路径'}"
                        break
            self.check_repo_status()
    
    def log(self, message):
        """添加日志信息"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)  # 滚动到最后
        self.log_text.config(state=tk.DISABLED)
    
    def run_git_commands(self):
        """执行git命令"""
        repo_path = self.repo_path.get()
        if not repo_path:
            self.log("请先选择Git仓库路径")
            return
        
        # 转换为绝对路径，避免相对路径可能出现的问题
        abs_repo_path = os.path.abspath(repo_path)
        
        if not os.path.isdir(os.path.join(abs_repo_path, ".git")):
            self.log("所选路径不是Git仓库")
            return
        
        try:
            self.log("开始执行更新...")
            
            # 执行git fetch --all
            fetch_result = subprocess.run(
                ["git", "fetch", "--all"],
                cwd=abs_repo_path,
                capture_output=True,
                text=True,
                check=True
            )
            self.log("git fetch --all 执行成功")
            
            # 执行git reset --hard origin/master
            reset_result = subprocess.run(
                ["git", "reset", "--hard", "origin/master"],
                cwd=abs_repo_path,
                capture_output=True,
                text=True,
                check=True
            )
            self.log("git reset --hard origin/master 执行成功")
            self.log("更新完成")
            
        except subprocess.CalledProcessError as e:
            self.log(f"命令执行失败: {e.stderr}")
        except Exception as e:
            self.log(f"发生错误: {str(e)}")
    
    def run_once(self):
        """立即执行一次更新"""
        threading.Thread(target=self.run_git_commands, daemon=True).start()
    
    def job(self):
        """定时任务"""
        self.run_git_commands()
    
    def start_scheduler(self, interval):
        """启动定时任务"""
        schedule.clear()
        schedule.every(interval).minutes.do(self.job)
        
        while self.is_running:
            schedule.run_pending()
            time.sleep(1)
    
    def start_updating(self):
        """开始定时更新"""
        try:
            interval = int(self.interval.get())
            if interval <= 0:
                messagebox.showerror("错误", "间隔时间必须大于0")
                return
        except ValueError:
            messagebox.showerror("错误", "请输入有效的数字")
            return
        
        if not self.repo_path.get():
            messagebox.showerror("错误", "请先选择Git仓库路径")
            return
        
        self.is_running = True
        self.start_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.NORMAL)
        self.run_once_btn.config(state=tk.DISABLED)
        
        self.log(f"开始定时更新，间隔 {interval} 分钟")
        
        # 启动定时任务线程
        self.schedule_thread = threading.Thread(
            target=self.start_scheduler,
            args=(interval,),
            daemon=True
        )
        self.schedule_thread.start()
        
        # 立即执行一次
        self.run_once()
    
    def stop_updating(self):
        """停止定时更新"""
        self.is_running = False
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.run_once_btn.config(state=tk.NORMAL)
        self.log("已停止定时更新")

if __name__ == "__main__":
    root = tk.Tk()
    app = GitAutoUpdater(root)
    root.mainloop()
    